﻿using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using Poet.ViewModels;

namespace Poet.Views
{
    /// <summary>
    /// Interaction logic for SearchView.xaml
    /// </summary>
    public partial class SearchView : INotifyPropertyChanged
    {
        private bool _isReplaceMode;

        /// <summary>
        /// Initializes a new instance of the <see cref="SearchView"/> class.
        /// </summary>
        public SearchView()
        {
            InitializeComponent();
            DataContextChanged += (sender, args) =>
                {
                    if (SearchViewModel != null)
                        ViewContextMenu.DataContext = ContextMenu.DataContext = SearchViewModel;
                };
            //SearchOptionsComboBox.Loaded += (o, e) =>
            //    {
            //        var comboBox = (ComboBox) o;

            //        comboBox.ApplyTemplate();
            //        var textBox = (TextBox) comboBox.Template.FindName("PART_EditableTextBox", comboBox);
            //        var brush = new LinearGradientBrush(Color.FromRgb(139, 139, 139), Color.FromRgb(119, 119, 119), 90.0);
            //        //var brush = new SolidColorBrush(Color.FromRgb(119, 119, 119));

            //        textBox.FontStyle = FontStyles.Italic;
            //        textBox.Foreground = brush;
            //        textBox.TextChanged += (sender, args) => textBox.Text = Localizing.ProvideValue("SetRequiredItems");
            //    };

            SearchItemsComboBox.Loaded += (o, e) =>
                {
                    var comboBox = (ComboBox)o;

                    comboBox.ApplyTemplate();
                    var textBox = (TextBox)comboBox.Template.FindName("PART_EditableTextBox", comboBox);
                    var brush = new LinearGradientBrush(Color.FromRgb(139, 139, 139), Color.FromRgb(119, 119, 119), 90.0);
                    //var brush = new SolidColorBrush(Color.FromRgb(119, 119, 119));

                    textBox.FontStyle = FontStyles.Italic;
                    textBox.Foreground = brush;

                    textBox.GotFocus += delegate
                        {
                            textBox.Text = string.Empty;
                            textBox.FontStyle = FontStyles.Normal;
                            textBox.Foreground = Brushes.Black;
                        };

                    textBox.LostFocus += delegate
                        {
                            var bindingExpressionBase =
                                BindingOperations.GetBindingExpressionBase(comboBox, ComboBox.TextProperty);
                            if (bindingExpressionBase != null)
                                bindingExpressionBase.UpdateTarget();

                            textBox.FontStyle = FontStyles.Italic;
                            textBox.Foreground = brush;
                        };

                    comboBox.DropDownClosed += delegate { comboBox.Items.Filter = null; };

                    textBox.KeyUp += (o1, e1) =>
                        {
                            comboBox.IsDropDownOpen = e1.Key != Key.Escape;
                            comboBox.Items.Filter = a =>
                                {
                                    var title = ((DocumentView)a).Title;
                                    if (title == null)
                                    {
                                        return false;
                                    }

                                    var containsSubstring = title.ToLower().Contains(textBox.Text.ToLower());
                                    if (containsSubstring)
                                    {
                                        return true;
                                    }

                                    foreach (var substring in textBox.Text.Split())
                                    {
                                        containsSubstring = title.ToLower().Contains(substring.ToLower());
                                        if (containsSubstring && !string.IsNullOrEmpty(substring))
                                        {
                                            return true;
                                        }
                                    }

                                    return false;
                                };
                        };
                };
        }

        public bool IsReplaceMode
        {
            get { return _isReplaceMode; }
            set { _isReplaceMode = value; OnPropertyChanged("IsReplaceMode"); }
        }

        private SearchViewModel SearchViewModel
        {
            get { return DataContext as SearchViewModel; }
        }

        private void IgnoreSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var comboBox = (ComboBox) sender;
            comboBox.SelectedItem = null;
        }

        private void Handle(object sender, RoutedEventArgs e)
        {
            e.Handled = true;
        }

        private void SelectableItem_OnPreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (SearchViewModel.LookInViewModel.ItemForMove == null)
            {
                return;
            }

            if (e.LeftButton != MouseButtonState.Pressed && e.RightButton != MouseButtonState.Pressed)
            {
                SearchViewModel.LookInViewModel.ItemForMove = null;
                return;
            }

            var control = (Control) sender;
            var documentView = (DocumentView) control.DataContext;

            if (Equals(documentView, SearchViewModel.LookInViewModel.ItemForMove))
            {
                return;
            }

            var newIndex = SearchViewModel.LookInViewModel.Items.IndexOf(documentView);
            var oldIndex = SearchViewModel.LookInViewModel.Items.IndexOf(SearchViewModel.LookInViewModel.ItemForMove);
            SearchViewModel.LookInViewModel.Items.Move(oldIndex, newIndex);

        }

        private void SelectableItem_OnMouseDown(object sender, MouseButtonEventArgs e)
        {
            var element = (FrameworkElement) sender;
            var move = e.RightButton == MouseButtonState.Pressed || element.Name == "MoveButton";
            SearchViewModel.LookInViewModel.ItemForMove = move ? element.DataContext as DocumentView : null;
            e.Handled = move;
        }

        private void SetActiveItem(object sender, RoutedEventArgs e)
        {
            var radioButton = (RadioButton)sender;
            var item = (DocumentView)radioButton.DataContext;

            if (SearchViewModel.ActiveDocumentView != null && !SearchViewModel.LookInViewModel.LastActiveItemCheckState)
            {
                SearchViewModel.LookInViewModel.SelectedItems.Remove(SearchViewModel.ActiveDocumentView);
            }

            SearchViewModel.ActiveDocumentView = item;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        private void ScrollMatch(object sender, MouseWheelEventArgs e)
        {
            if (Keyboard.Modifiers == ModifierKeys.Control)
            {
                ApplicationCommands.Replace.Execute(e.Delta > 0 ? "Back" : "Next", this);
            }
            else
            {
                if (e.Delta > 0 && ScrollBar.Value > ScrollBar.Minimum)
                    ScrollBar.Value--;

                if (e.Delta < 0 && ScrollBar.Value <= ScrollBar.Maximum)
                    ScrollBar.Value++;
            }

            e.Handled = true;
        }

        private void SearchView_OnMouseDown(object sender, MouseButtonEventArgs e)
        {
            if(e.MiddleButton == MouseButtonState.Pressed)
                ApplicationCommands.Replace.Execute("Single", this);
        }
    }
}
